const router = require("koa-router")();
const {
  findNoteListByType,
  findNoteListById,
  saveNotePublish,
} = require("../controllers/index.js");
const jwt = require("../utils/jwt.js");

router.get("/findNoteListByType", jwt.verify(), async (ctx) => {
  //获取前端传递的 note_type,去数据库中以该note_type字段 读取数据，返回给前端
  //console.log(ctx.request.query)
  const { note_type } = ctx.request.query;
  //console.log(ctx.userId,'-----');
  // const res=await findNoteListByType(note_type);
  // console.log(res)

  try {
    const res = await findNoteListByType(note_type, ctx.userId);
    //console.log(res);
    if (res.length) {
      ctx.body = {
        code: "8000",
        data: res,
        msg: "查询成功",
      };
    } else {
      ctx.body = {
        code: "8000",
        data: "success",
        msg: "当前分类下没有数据",
      };
    }
  } catch (error) {
    ctx.body = {
      code: "8005",
      data: error, //不用打引号，因为error是object
      msg: "服务器异常",
    };
  }
});

router.get("/findNoteListById", jwt.verify(), async (ctx) => {
  //获取前端传递的 id,去数据库中以该id字段 读取数据，返回给前端
  //console.log(ctx.request.query,'222222')
  const { id } = ctx.request.query;
  // console.log(res)
  try {
    const res = await findNoteListById(id);
    //console.log(res);
    ctx.body = {
      code: "8000",
      data: res,
      msg: "查询成功",
    };
  } catch (error) {
    ctx.body = {
      code: "8005",
      data: error,
      msg: "服务器异常",
    };
  }
});

router.post("/note-publish", jwt.verify(), async (ctx) => {
  //console.log("22222");
  const { title, note_type, head_img, note_content, nickname, userId } =
    ctx.request.body;
  try {
    const res = await saveNotePublish(
      title,
      note_type,
      head_img,
      note_content,
      nickname,
      userId
    );
    //console.log(res);
    ctx.body = {
      code: "8000",
      data: res,
      msg: "插入成功",
    };
  } catch (error) {
    ctx.body = {
      code: "8006",
      data: error,
      msg: "服务器异常",
    };
  }
});

module.exports = router;
